package xps.and.uudaijia.userclient.presenter;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.jude.utils.JUtils;

import xps.and.uudaijia.userclient.App;
import xps.and.uudaijia.userclient.util.GlobalPositionInfo;
import xps.and.uudaijia.userclient.view.activity.DownloadOfflineMapActivity;

public class OfflineMapPresenter extends BasePresenter<DownloadOfflineMapActivity> implements MKOfflineMapListener {
    private MKOfflineMap mOffline;
    private int cityCode = -1;
    MKOLUpdateElement offlineMap = null;
    GlobalPositionInfo globalPositionInfo;

    @Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        initPositionRelated();
    }

    /**
     * 位置相关
     */
    private void initPositionRelated() {
        mOffline = new MKOfflineMap();
        mOffline.init(this);

        try {
            globalPositionInfo = App.getInstance().getGloPosinfo();
            cityCode = Integer.valueOf(globalPositionInfo.bdLocation.getCityCode());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 返回地图是否已离线
     */
    public boolean getOfflineState() {
        if (mOffline == null || mOffline.getAllUpdateInfo() == null) return false;
        if (mOffline.getAllUpdateInfo().size() >= 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 使用当前定位地址的citycode缓存地图
     *
     * @param context
     */
    public void start(Activity context) {
        if (cityCode == -1 || mOffline == null) return;
        mOffline.start(cityCode);
        Toast.makeText(context, "开始下载离线地图", Toast.LENGTH_SHORT)
                .show();
        updateView();
    }

    /**
     * 更新状态显示
     */
    private void updateView() {
        if (mOffline.getAllUpdateInfo() == null && mOffline.getAllUpdateInfo().size() <= 0) return;
        offlineMap = mOffline.getAllUpdateInfo().get(0);
    }

    @Override
    protected void onTakeView(DownloadOfflineMapActivity da) {
        super.onTakeView(da);
        if (mOffline != null && mOffline.getAllUpdateInfo() != null)
            offlineMap = mOffline.getAllUpdateInfo().get(0);
    }

    /**
     * 移除地图缓存
     */
    public void removeOfflineData() {
        if (mOffline == null || mOffline.getAllUpdateInfo().size() <= 0)
            return;
        if (mOffline.remove(cityCode)) {
            JUtils.Toast("离线地图已删除");
        } else {
            JUtils.Toast("删除失败");
        }
    }

    @Override
    public void onGetOfflineMapState(int i, int i1) {

    }
}
